//
//  SelectViewController.m
//  project
//
//  Created by 张振宇 on 15/10/26.
//  Copyright © 2015年 lanou. All rights reserved.
//

#import "SelectViewController.h"
#import "MainTableViewController.h"
#import "PKRequestManager.h"
#import "ShufflingModel.h"
#import "MainBtnModel.h"
#import "OtherTableViewModel.h"
#import "UIScrollView+MJRefresh.h"
#import <UIButton+WebCache.h>
#import "MJRefresh.h"
#import "MainWebController.h"
#import "LZAutoScrollView.h"
#import "CatogryAllSpecialDetailViewController.h"
#import "MainZenoViewController.h"
#import "OtherTableViewController.h"
#import "MainJokesViewController.h"
#import "MainMHViewController.h"
#import "FMDatabase.h"
@interface SelectViewController ()<UIScrollViewDelegate,LZAutoScrollViewDelegate>
@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,strong) UIView *headerView;
@property (nonatomic, strong) MainTableViewController *maintableVC;
@property (nonatomic, strong) NSMutableArray *shufflingArr;
@property (nonatomic, strong) NSMutableArray *buttonArr;
@property (nonatomic, strong) NSMutableArray *dateArr;

@property (nonatomic, strong) LZAutoScrollView *autoScrollView;

@property (nonatomic, copy) NSString *next_url;
@property (nonatomic, strong)FMDatabase *dataBase;
@end

@implementation SelectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self requestData];
    _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kWidth, 300)];
    _autoScrollView = [[LZAutoScrollView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 200)];
    _autoScrollView.delegate = self;
    [_headerView addSubview:_autoScrollView];
 
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 200, kWidth, 150)];
    [_headerView addSubview:view];
    _maintableVC = [[MainTableViewController alloc]initWithStyle:UITableViewStylePlain];
    _maintableVC.navigationC = self.navigationC;
    _maintableVC.tableView.frame =CGRectMake(0, 0, kWidth, kHeight - 100);
    _maintableVC.tableView.footer = [MJRefreshBackFooter footerWithRefreshingBlock:^{
        [self reloadData];
    }];
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestData)];
    NSArray *arr = @[[UIImage imageNamed:@"1.tiff"],[UIImage imageNamed:@"2.tiff"],[UIImage imageNamed:@"3.tiff"],[UIImage imageNamed:@"4.tiff"]];
    [header setImages:arr forState:MJRefreshStateRefreshing];
    header.lastUpdatedTimeLabel.hidden = YES;
    header.stateLabel.hidden = YES;
    _maintableVC.tableView.header = header;
    _maintableVC.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _maintableVC.tableView.tableHeaderView = _headerView;
    [self.view addSubview:_maintableVC.tableView];
    
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"project.db"];
     _shufflingArr = [NSMutableArray arrayWithCapacity:0];
    _dateArr = [NSMutableArray arrayWithCapacity:0];
    _buttonArr = [NSMutableArray arrayWithCapacity:0];

    
    
    _dataBase = [FMDatabase databaseWithPath:filePath];
    
    if ([_dataBase open])
    {
        
        [_dataBase executeUpdate:@"create table HeaderData (data blob)"];
        [_dataBase executeUpdate:@"create table CollectionData (data blob)"];
        [_dataBase executeUpdate:@"create table TableViewData (data blob)"];
        
    }
    else
    {
        NSLog(@"数据库打开失败");
    }
    
    FMResultSet *resultSet1 = [_dataBase executeQuery:@"select * from HeaderData"];
    
    while ([resultSet1 next])
    {
        NSData *data = [resultSet1 dataForColumn:@"data"];
        NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
       
        for (NSDictionary *dic in dict[@"data"][@"banners"]) {
            ShufflingModel *model = [[ShufflingModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            //NSLog(@"%@",model.cover_image_url);
            [_shufflingArr addObject:model];
        }
        

    }
    
    if (_shufflingArr.count != 0)
    {
        [self createShuffling];
    }
    
    FMResultSet *resultSet = [_dataBase executeQuery:@"select * from CollectionData"];
    
    while ([resultSet next])
    {
        NSData *data = [resultSet dataForColumn:@"data"];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        for (NSDictionary *btnDic in dic[@"data"][@"promotions"]) {
            MainBtnModel *model = [[MainBtnModel alloc]init];
            [model setValuesForKeysWithDictionary:btnDic];
            [_buttonArr addObject:model];
            
        }
        
    }
    
    if (_buttonArr.count != 0)
    {
        [self createBtn];

    }
    
    
    FMResultSet *resultSet2 = [_dataBase executeQuery:@"select * from TableViewData"];
    
    while ([resultSet2 next])
    {
        NSData *data = [resultSet dataForColumn:@"data"];
        if (data == nil)
        {
            return;
        }
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
              _next_url = dict[@"data"][@"paging"][@"next_url"];
        for (NSDictionary *tabDic in dict[@"data"][@"items"]) {
            OtherTableViewModel *model = [[OtherTableViewModel alloc]init];
            [model setValuesForKeysWithDictionary:tabDic];
            if (model.cover_image_url == nil) {
            }
            else{
                
                [_dateArr addObject:model];
            }
        }
 
        
    }
    
    if (_dateArr.count != 0)
    {
        _maintableVC.dataArr = _dateArr;
        [_maintableVC.tableView reloadData];

    }


    
   [self requestData];

    //self.view.backgroundColor = [UIColor redColor];
    // Do any additional setup after loading the view.
}

- (void)requestData
{
    NSString *str = [NSString stringWithFormat:@"http://api.liwushuo.com/v2/banners?channel=iOS"];
    [PKRequestManager requestWithTypeP:GET urlString:str parDic:nil finish:^(NSData *data) {
        [_dataBase executeUpdate:@"delete from HeaderData"];
        [_dataBase executeUpdate:@"insert into HeaderData values (?)", data];
        NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
      
        [_shufflingArr removeAllObjects];
        for (NSDictionary *dic in dict[@"data"][@"banners"]) {
            ShufflingModel *model = [[ShufflingModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            //NSLog(@"%@",model.cover_image_url);
            [_shufflingArr addObject:model];
        }
        [self createShuffling];
        
        
    } error:^(NSError *error) {
        
    }];
    
    NSString *btnStr = [NSString stringWithFormat:@"http://api.liwushuo.com/v2/promotions?gender=1&generation=1"];
    [PKRequestManager requestWithTypeP:GET urlString:btnStr parDic:nil finish:^(NSData *data) {
        [_dataBase executeUpdate:@"delete from CollectionData"];
        [_dataBase executeUpdate:@"insert into CollectionData values (?)", data];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [_buttonArr removeAllObjects];
        for (NSDictionary *btnDic in dic[@"data"][@"promotions"]) {
            MainBtnModel *model = [[MainBtnModel alloc]init];
            [model setValuesForKeysWithDictionary:btnDic];
            [_buttonArr addObject:model];

        }
        [self createBtn];
        
    } error:^(NSError *error) {
        
    }];
    NSString *tableStr = [NSString stringWithFormat:@"http://api.liwushuo.com/v2/channels/100/items?ad=1&gender=1&generation=1&limit=20&offset=0"];
    [PKRequestManager requestWithTypeP:GET urlString:tableStr parDic:nil finish:^(NSData *data){
        [_dataBase executeUpdate:@"delete from TableViewData"];
        [_dataBase executeUpdate:@"insert into TableViewData values (?)", data];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [_dateArr removeAllObjects];
        _next_url = dict[@"data"][@"paging"][@"next_url"];
        for (NSDictionary *tabDic in dict[@"data"][@"items"]) {
            OtherTableViewModel *model = [[OtherTableViewModel alloc]init];
            [model setValuesForKeysWithDictionary:tabDic];
            if (model.cover_image_url == nil) {
            }
            else{
            
            [_dateArr addObject:model];
            }
        }
        [_maintableVC.tableView.header endRefreshing];
        _maintableVC.dataArr = _dateArr;
        [_maintableVC.tableView reloadData];
    }error:nil];
    
}

- (void)reloadData
{
    [PKRequestManager requestWithTypeP:GET urlString:_next_url parDic:nil finish:^(NSData *data){
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        _next_url = dict[@"data"][@"paging"][@"next_url"];
        for (NSDictionary *tabDic in dict[@"data"][@"items"]) {
            OtherTableViewModel *model = [[OtherTableViewModel alloc]init];
            [model setValuesForKeysWithDictionary:tabDic];
            [_dateArr addObject:model];
        }
        
        _maintableVC.dataArr = _dateArr;
        [_maintableVC.tableView.footer endRefreshing];
        [_maintableVC.tableView reloadData];
    }error:nil];
}

- (void)imageClicked:(NSInteger)index {
    NSLog(@"index: %@", ((ShufflingModel *)_shufflingArr[index]).target.Myid);
    ShufflingModel *model = _shufflingArr[index];
    if ([model.type isEqualToString:@"collection"]) {
        CatogryAllSpecialDetailViewController *otherTableVC = [[CatogryAllSpecialDetailViewController alloc]init];
        otherTableVC.id = [NSNumber numberWithInteger:[model.target.Myid integerValue]];
        otherTableVC.hidesBottomBarWhenPushed = YES;
        [self.navigationC pushViewController:otherTableVC animated:YES];
        otherTableVC.hidesBottomBarWhenPushed = NO;
    }
    else{
        MainWebController *mainWC = [[MainWebController alloc]init];
        mainWC.url = model.target_url;
        mainWC.hidesBottomBarWhenPushed = YES;
        [self.navigationC pushViewController:mainWC animated:YES];
        mainWC.hidesBottomBarWhenPushed = NO;
    }
    
}

- (void)createBtn
{
    for (int i = 0; i < 4;i++ ) {
        MainBtnModel *model = _buttonArr[i];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.tag = i;
        btn.frame = CGRectMake(i * kWidth / 4, 200, kWidth / 4, 100);
        
        [btn sd_setImageWithURL:[NSURL URLWithString:model.icon_url] forState:UIControlStateNormal];
        if (i == 2) {
            [btn setTitle:@"每日段子" forState:UIControlStateNormal];
        }
        else if (i == 3)
        {
            [btn setTitle:@"第一星座" forState:UIControlStateNormal];
        }
        else
        {
        [btn setTitle:model.title forState:UIControlStateNormal];
        }
        btn.titleLabel.font = [UIFont systemFontOfSize:16];
        btn.imageEdgeInsets = UIEdgeInsetsMake(21,21,21,btn.titleLabel.bounds.size.width+21);
        [btn setTitleColor:[self colorWithHexString:model.color]forState:UIControlStateNormal];
        btn.titleEdgeInsets = UIEdgeInsetsMake(80, -btn.titleLabel.bounds.size.width-80, 0, 0);
        [btn addTarget:self action:@selector(didClickChange:) forControlEvents:UIControlEventTouchUpInside];
        [_headerView addSubview:btn];
        
    }
}

- (UIColor *) colorWithHexString: (NSString *)color
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
   return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
   
}

- (void)createShuffling
{
    NSMutableArray *arr = [NSMutableArray arrayWithCapacity:0];
    for (int i = 0; i < 6; i ++) {
        ShufflingModel *model = _shufflingArr[i];
        [arr addObject:model.image_url];
    }
    _autoScrollView.images = arr;
    [_autoScrollView createViews];
    
}

- (void)didClickChange:(UIButton *)btn
{
    
    if(btn.tag == 1)
    {
        MainZenoViewController *mainZenoVC = [[MainZenoViewController alloc]init];
        [self.navigationC pushViewController:mainZenoVC animated:YES];
    }
    else if (btn.tag == 0)
    {
        MainMHViewController *otherTableVC = [[MainMHViewController alloc]init];
        otherTableVC.contentId = @"22";
        otherTableVC.navigationC = self.navigationC;
        [self.navigationC pushViewController:otherTableVC animated:YES];
    }
    else if(btn.tag == 2)
    {
        MainJokesViewController *jokesVC = [[MainJokesViewController alloc]init];
        [self.navigationC pushViewController:jokesVC animated:YES];
    }
    else
    {
        MainWebController *webView = [[MainWebController alloc]init];
        webView.url = @"http://3g.d1xz.net";
        webView.navigationItem.title = @"第一星座";
        [self.navigationC pushViewController:webView animated:YES];
        
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
